package com.wuniutech.notebook

import android.app.Application
import android.content.Context
import com.tencent.smtt.sdk.QbSdk

//import com.tencent.smtt.sdk.QbSdk


class AppContext : Application() {

    override fun onCreate() {
        super.onCreate()
        appContext = this //程序崩溃异常捕获并自动重启
        Thread.setDefaultUncaughtExceptionHandler(restartHandler) //初始化基础模块上下文
        createImageFolder() // 在Application中初始化X5内核
        //在Application中初始化X5内核
        QbSdk.initX5Environment(this, object : QbSdk.PreInitCallback {
            override fun onCoreInitFinished() {}
            override fun onViewInitFinished(isX5: Boolean) {}
        })

        // 替换系统WebView为com.tencent.smtt.sdk.WebView
    }

    companion object {
        private lateinit var appContext: AppContext

        @Synchronized
        fun getContext(): Context {
            return appContext
        }
    }

    private val restartHandler =
        Thread.UncaughtExceptionHandler { _: Thread?, e: Throwable -> //        LogFileUtils.writeTxtToFile("程序异常：$e")

            //        val intent = Intent(this, MainActivity::class.java) //重启应用，得使用PendingIntent
            //        val restartIntent = PendingIntent.getActivity(this,
            //            0,
            //            intent,
            //            PendingIntent.FLAG_CANCEL_CURRENT or PendingIntent.FLAG_IMMUTABLE)
            //        val mAlarmManager = getSystemService(ALARM_SERVICE) as AlarmManager
            //        mAlarmManager[AlarmManager.RTC, System.currentTimeMillis() + 2000] =
            //            restartIntent // 2秒钟后重启应用
            //        AppManager.getAppManager().finishAllActivity() //退出程序
            //        Process.killProcess(Process.myPid()) //结束当前进程

        }

    /**
     * 创建图片保存文件夹
     */
    private fun createImageFolder() {
        val imagePath = getExternalFilesDir("image")
        val videoPath = getExternalFilesDir("video")
        val filePath = getExternalFilesDir("file_path")
        val logPath =
            getExternalFilesDir("log") //        GlobalVariables.setImagePath(imagePath?.absolutePath ?: "") //        GlobalVariables.setVideoPath(videoPath?.absolutePath ?: "") //        GlobalVariables.setFilePath(filePath?.absolutePath ?: "") //        GlobalVariables.setLogPath(logPath?.absolutePath ?: "")
    }

}